import axios, { AxiosError } from 'axios';
import type { AxiosResponse, AxiosRequestConfig } from 'axios';
import type { IConfigType } from '@/types/request';
import { getMessageInfo } from './status';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { useUserStoreHook } from '@/stores/user';
import { debounce } from 'lodash';
import app from '@/main.ts';

let LoadingRequestCount = 0;
const showLoading = () => {
    if (LoadingRequestCount === 0) app.config.globalProperties.$Loading.showLoading();
    LoadingRequestCount++;
};
const hideLoading = () => {
    LoadingRequestCount--;
    LoadingRequestCount = Math.max(LoadingRequestCount, 0);
    if (LoadingRequestCount === 0) toHideLoading();
};

const toHideLoading = debounce(() => {
    app.config.globalProperties.$Loading.hideLoading();
}, 100);

const service = axios.create({
    // baseURL: import.meta.env.VITE_APP_DEV_USE_MOCK
    //     ? import.meta.env.VITE_APP_MOCK_BASEURL
    //     : import.meta.env.VITE_APP_API_BASEURL,
    timeout: 15000
});

// axios实例拦截请求
service.interceptors.request.use(
    (config: IConfigType) => {
        if (config?.isShowLoading !== false) showLoading();
        const { factoryId, accessToken } = useUserStoreHook();
        config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
        config.headers['Factory-Id'] = factoryId;
        config.headers[website.tokenHeader] = 'bearer ' + accessToken;
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    }
);
// axios实例拦截响应
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const config = response.config as IConfigType;
        if (config?.isShowLoading !== false) hideLoading();
        if (response.status === 200) {
            return response;
        }
        ElMessage({
            message: getMessageInfo(response.status),
            type: 'error'
        });
        return response;
    },
    // 请求失败
    (error: any) => {
        hideLoading();
        const { response } = error;
        if (response) {
            ElMessage({
                message: getMessageInfo(response.status),
                type: 'error'
            });
            return Promise.reject(response.data);
        }
        ElMessage({
            message: '网络连接异常,请稍后再试!',
            type: 'error'
        });
    }
);

export default service;
